
#include "Common.h"
#include "HttpResponseHeader.h"
namespace fx {

    HttpResponseHeader::~HttpResponseHeader()
    {

    }

    HttpResponseHeader::HttpResponseHeader()
    {
    }

    HttpResponseHeaderPtr HttpResponseHeader::Create()
    {
        return HttpResponseHeaderPtr(new HttpResponseHeader());
    }
    HttpResponseHeaderPtr HttpResponseHeader::Create(const std::string& str_buf)
    {
        HttpResponseHeaderPtr header = HttpResponseHeader::Create();
        if (header->Parse(str_buf)) {
            return header;
        }
        return HttpResponseHeaderPtr();
    }
    HttpResponseHeaderPtr HttpResponseHeader::Create(std::istream& iss)
    {
        HttpResponseHeaderPtr header = HttpResponseHeader::Create();
        if (header->Parse(iss)) {
            return header;
        }
        return HttpResponseHeaderPtr();
    }

    bool HttpResponseHeader::ParseFirstLine()
    {
        boost::uint32_t offset = 0, next_offset = 0;

        offset = first_line_.find(' ', offset);
        if (std::string::npos == offset) return false;
        protocol_ = first_line_.substr(0, offset);

        offset = first_line_.find_first_not_of(' ', offset);
        if (std::string::npos == offset) return false;

        next_offset = first_line_.find(' ', offset);
        if (std::string::npos == next_offset) return false;
        code_ = first_line_.substr(offset, next_offset - offset);

        offset = first_line_.find_first_not_of(' ', next_offset);
        if (std::string::npos == next_offset) return false;

        description_ = first_line_.substr(offset);

        // version
        std::vector<std::string> results;
        boost::algorithm::split(results, protocol_, boost::is_any_of("/"));
        if (results.size() != 2) return false;

        protocol_ = boost::algorithm::trim_copy(results[0]);
        version_ = boost::algorithm::trim_copy(results[1]);

        return true;
    }

    void HttpResponseHeader::UpdateFirstLine()
    {
        first_line_ = (protocol_ + "/" + version_ + " " + code_ + " " + description_);
    }

    void HttpResponseHeader::SetCode(const std::string& code)
    {
        if (code != code_) {
            code_ = code;
            UpdateFirstLine();
        }
    }

    void HttpResponseHeader::SetDescription(const std::string& description)
    {
        if (description != description_) {
            description_ = description;
            UpdateFirstLine();
        }
    }
    void HttpResponseHeader::SetProtocol(const std::string& protocol)
    {
        if (protocol != protocol_) {
            protocol_ = protocol;
            UpdateFirstLine();
        }
    }
    void HttpResponseHeader::SetVersion(const std::string& version)
    {
        if (version != version_) {
            version_ = version;
            UpdateFirstLine();
        }
    }

}